package testApplets;

import processing.core.PApplet;
import processing.core.PImage;
import simpleGeom.Vec2D;

public class SkewApplet extends PApplet {
	int nX;
	int nY;
	PImage img;
	float cX = 10;
	float cY = 50;
	Vec2D center=new Vec2D();
	float[] line2 = new float[] { -10, 400.54f, 400, -10.2f };
	float[] line1 = new float[] { -10, 200.16f, 200, -10.3f };

	public void skew() {
		Vec2D point = new Vec2D();
		for (int x = 1; x < nX; x++) {
			for (int y = 1; y < nY; y++) {
				point.x = x;
				point.y = y;
				Vec2D i1 = lineLineIntersection(cX, cY, x, y, line1[0],
						line1[1], line1[2], line1[3]);
				float dTarget1 = dist(cX, cY, i1.x, i1.y);
				Vec2D i2 = lineLineIntersection(cX, cY, x, y, line2[0],
						line2[1], line2[2], line2[3]);
				float d1 = dist(cX,cY, x, y);
				float dTarget2 = dist(cX, cY, i2.x, i2.y);
				
				if (d1>dTarget1&&d1<dTarget2){
					float newd = map(d1, dTarget1, dTarget2, 0, dTarget2);
					Vec2D v = Vec2D.sub(point, center);
					v.setLength(newd);
					Vec2D newP = Vec2D.add(center, v);
					float srcX1 = (int) newP.x;
					float srcX2 = (int) newP.x + 1;
					float srcY1 = (int) newP.y;
					float srcY2 = (int) newP.y + 1;
					int col=getColor((int)newP.x,(int)newP.y);
					setColor(x,y,col);
				}
			}
		}
	}
	
	public void setup() {
		img = this.loadImage("/Users/caad/Desktop/FuBK-TestbildGrey.png");
		
		nX = img.width;
		nY = img.height;
		size(nX,nY);
		
		
	}
	public void setColor(int x,int y,int c){
		pixels[x+y*nX]=c;
	}
	public int getColor(int x,int y){
		return img.pixels[x+y*nX];
	}
	public void draw() {
		image(img,0,0);
		loadPixels();
		skew();
		updatePixels();
		//image(img, 0, 0);
		stroke(255, 0, 0);
		line(line1[0], line1[1], line1[2], line1[3]);
		line(line2[0], line2[1], line2[2], line2[3]);
	}

	public static Vec2D lineLineIntersection(float aX, float aY, float bX,
			float bY, float cX, float cY, float dX, float dY) {
		float denominator = ((bX - aX) * (dY - cY)) - ((bY - aY) * (dX - cX));
		if (denominator == 0)
			return null;// parallel
		float numerator = ((aY - cY) * (dX - cX)) - (aX - cX) * (dY - cY);
		float numerator2 = ((aY - cY) * (bX - aX)) - ((aX - cX) * (bY - aY));
		float r = numerator / denominator;
		float s = numerator2 / denominator;
		float x = aX + r * (bX - aX);
		float y = aY + r * (bY - aY);
		return new Vec2D( x,  y);
	}
}
